package com.bba.cloud.search.service.impl;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bba.cloud.search.mapper.CustomerESMapper;
import com.bba.cloud.search.service.ICustomerESService;
import com.bba.manager.common.model.search.CustomerES;
import com.bba.manager.common.model.user.VO.customerPageVO;
import com.bba.manager.common.util.ResponseEnum;
import com.bba.manager.common.util.ResponseVO;
import com.bba.manager.user.customerFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustormerESImpl implements ICustomerESService {
    @Autowired
    private customerFeign customerfeigngn;
    @Autowired
    private CustomerESMapper customerESMapper;
    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Override
    public void saveAll() {
        ResponseVO list = customerfeigngn.list();
        if(list.getCode()!= ResponseEnum.SUCCESS.getCode()){
            throw new RuntimeException(list.getMessage());
        }
        List<CustomerES> customerES = JSON.parseArray(JSON.toJSONString(list.getData()) , CustomerES.class);
        customerESMapper.saveAll(customerES);
    }


    @Override
    public void save(CustomerES customerES) {
        // 保存单个商品到ES
       customerESMapper.save(customerES);
    }

    @Override
    public void deleteById(Long id) {
        // 根据ID删除商品
       customerESMapper.deleteById(id);
    }

    @Override
    /**
     * 分页查询客户信息
     * @param customerPageVO 客户分页查询条件对象
     * @return 返回分页结果
     */
    public IPage page(customerPageVO customerPageVO) {
//构建查询条件
        NativeQueryBuilder wapper= NativeQuery.builder();
        List<Query> queryList = new ArrayList<>();
        // 添加各个查询条件的布尔查询
        boolQuery(queryList,"id",customerPageVO.getId());
        boolQuery(queryList,"name",customerPageVO.getName());
        boolQuery(queryList,"phone",customerPageVO.getPhone());
        boolQuery(queryList,"idCard",customerPageVO.getIdCard());
        // 设置分页参数
        Page<CustomerES> page = new Page<>(customerPageVO.getPage(), customerPageVO.getLimit());
        // 构建布尔查询条件
        wapper.withQuery(query -> query.bool(bool -> bool.must(queryList)));
        // 执行ES查询
        SearchHits<CustomerES> hits = esTemplate.search(wapper.build(), CustomerES.class);
        // 获取总记录数
        long total = hits.getTotalHits();
        // 设置总记录数到分页对象中
        page.setTotal(total);
        List<CustomerES> skuEsList = hits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
        // 获取当前页数据
        // 将查询结果转换为对象列表
        page.setRecords(skuEsList);
        // 返回查询结果（当前代码返回null，实际应返回分页结果）
        return page;
    }
    private void boolQuery(List<Query> queryList,String filed,Object value) {
        if(value!=null){
            Query query = Query.of(builder ->
                    builder.match(match ->
                            match.field(filed).query(value.toString())
                    )
            );
            queryList.add(query);
        }
    }
}
